package org.example.mytest.Service;


import org.example.mytest.emnu.Status;
import org.example.mytest.entity.Shouhoudan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Objects;

import static org.example.mytest.emnu.Status.REJECTED;


@Service
@ComponentScan

public class AfterSaleService
{

    private Shouhoudan[] orderArray = new Shouhoudan[1];//初始化数组
    private int size = 0; // 记录实际订单数量（数组中有效元素数）
    private static final String AUDITED = "已审核";
    public Shouhoudan[] getArrayinfo() {
        Shouhoudan[] Result = new Shouhoudan[size];
        System.arraycopy(orderArray, 0, Result, 0, size);//复制Shouhoudanzhong 的数据到Result数组中去查询
        return Result;
    }//获取存储的信息
    public Shouhoudan createOrder(Shouhoudan order){
        // 1. 遍历数组，检查是否存在核心字段相同的订单
        int sameCoreIndex = -1; // 记录核心字段相同的订单索引（初始为-1）
        for (int i = 0; i < size; i++) {
            Shouhoudan existing = orderArray[i];

            // 检查核心字段是否相同（商品名、手机号、客户名、门店）
            boolean coreFieldsMatch = Objects.equals(existing.getShangpinname(), order.getShangpinname())
                    && Objects.equals(existing.getPhone(), order.getPhone())
                    && Objects.equals(existing.getCustomername(), order.getCustomername())
                    && Objects.equals(existing.getMendian(), order.getMendian());

            if (coreFieldsMatch) {
                sameCoreIndex = i; // 记录核心字段相同的订单索引
                break;
            }
        }

        // 2. 根据核心字段匹配结果处理
        if (sameCoreIndex != -1) {
            // 核心字段相同：检查问题（question）是否不同
            Shouhoudan existing = orderArray[sameCoreIndex];//发现只有问题不同，则覆盖问题描述，避免再次创建售后单
            if (!Objects.equals(existing.getQuestion(), order.getQuestion())) {
                existing.setQuestion(order.getQuestion()); // 只更新问题描述
                // 可选：若需要记录更新时间，可同步更新
                return existing; // 返回更新后的原订单
            } else {
                // 问题也相同：视为完全重复，抛异常
                throw new RuntimeException("该售后单已提交（所有信息完全相同）");
            }
        }

        // 2. 数组扩容：当元素数达到容量时，扩容为原来的2倍
        if (size >= orderArray.length) {
            Shouhoudan[] newArray = new Shouhoudan[orderArray.length * 2];//新数组扩大到原来的两倍
            System.arraycopy(orderArray, 0, newArray, 0, size);//把原来数组中的数据复制到新数组中去
            orderArray = newArray;
        }
        printCount();//后台打印订单数量（方便测试）
        // 3. 存储新订单
        order.init();
        orderArray[size] = order;
        size++;
        return order;
    }//创建表单
    public void printCount() {
        int realesize = size + 1;
        System.out.println("当前售后单总数量：" + realesize);
    }//后台打印总数
    public Shouhoudan[] queryList(LocalDateTime time, String shangpinname) {
        // 步骤1：统计符合条件的订单数量
        int matchCount = 0;
        for (int i = 0; i < size; i++) { // size是数组中实际订单数量//遍历数组寻找符合条件的元素
            Shouhoudan order = orderArray[i];
            if (isMatch(order, time, shangpinname)) {
                matchCount++;
            }
        }

        // 步骤2：创建结果数组（容量=符合条件的数量）
        Shouhoudan[] result = new Shouhoudan[matchCount];
        int resultIndex = 0;//初始化下标

        // 步骤3：再次遍历，将符合条件的订单存入结果数组
        for (int i = 0; i < size; i++) {
            Shouhoudan order = orderArray[i];
            if (isMatch(order, time, shangpinname)) {
                result[resultIndex++] = order; // 直接存入原始订单对象，移动索引
            }
        }
        return result;
    }//按需查询表单
    private boolean isMatch(Shouhoudan order, LocalDateTime time, String shangpinname) {
        // 1. 时间条件：time为null则匹配所有；否则需订单时间非空且相等
        boolean timeMatch = (time == null)
                || (order.getTime() != null && order.getTime().equals(time));

        // 2. 商品名条件：shangpinname为null则匹配所有；否则需商品名非空且包含关键词（模糊匹配）
        boolean productMatch = (shangpinname == null)
                || (order.getShangpinname() != null && order.getShangpinname().contains(shangpinname));

        return timeMatch && productMatch; // 同时满足两个条件才算匹配
    }//判断是不是符合条件
    public Shouhoudan getDetailById(String id) {
        // 遍历数组中已存储的订单（仅遍历有效元素，即0到size-1）
        for (int i = 0; i < size; i++) {
            Shouhoudan order = orderArray[i];

            if (Objects.equals(order.getId(), id)) {
                return order; // 找到匹配的订单，直接返回
            }
        }
        // 遍历结束仍未找到，抛出异常
        throw new RuntimeException("售后单不存在");
    }//同过ID查询
    public void audit(String id, Status status) {
        Shouhoudan order = getDetailById(id);

        // 校验状态：仅待审核状态可操作
        if (order.getStatus() != Status.PENDING) {
            throw new RuntimeException("当前订单状态不允许审核（已审核）");
        }

        order.setStatus(status);
    }//审核操作
    public Shouhoudan[] getoveraudits() {
        int auditedCount = 0;
        for (int i = 0; i < size; i++) {
            Shouhoudan order = orderArray[i];
            if (order != null && isStatusAudited(order)) {
                auditedCount++;
            }
        }
        if (auditedCount == 0) {
            throw new RuntimeException("当前还未有已审核售后单");
        }
        Shouhoudan[] auditedArray = new Shouhoudan[auditedCount];
        int resultIndex = 0;
        for (int i = 0; i < size; i++) {
            Shouhoudan order = orderArray[i];

            if (order != null && isStatusAudited(order)) {
                auditedArray[resultIndex] = order;
                resultIndex++;
            }
        }

        return auditedArray;
    }//打印已经审核名单
    private boolean isStatusAudited(Shouhoudan order) {
        return Objects.equals(order.getStatus(), AUDITED);
    }
    public Shouhoudan[] getrejectedaudits() {
        int auditedCount = 0;
        for (int i = 0; i < size; i++) {
            Shouhoudan order = orderArray[i];
            if (order != null && isStatusRejected(order)) {
                auditedCount++;
            }
        }
        if (auditedCount == 0) {
            throw new RuntimeException("当前还未有已拒绝售后单");
        }
        Shouhoudan[] auditedArray = new Shouhoudan[auditedCount];
        int resultIndex = 0;
        for (int i = 0; i < size; i++) {
            Shouhoudan order = orderArray[i];

            if (order != null && isStatusRejected(order)) {
                auditedArray[resultIndex] = order;
                resultIndex++;
            }
        }

        return auditedArray;
    }//打印拒绝审核名单
    private boolean isStatusRejected(Shouhoudan order) {
        return Objects.equals(order.getStatus(), REJECTED);
    }
}
